<template>
  <div class="app-container">
    <el-form :inline="true">
      <el-form-item label="数据源名称">
        <el-input
          v-model="queryParams.datasourceName"
          placeholder="请输入数据源名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button type="primary" icon="el-icon-plus" size="small" @click="handleAdd">新增</el-button>
      </el-form-item>
    </el-form>
    <el-table
      v-loading="loading"
      :data="datasourceList"
      row-key="id"
      border
    >
      <el-table-column prop="datasource" label="数据源" :show-overflow-tooltip="true" width="160"></el-table-column>
      <el-table-column prop="datasourceName" label="数据源名称" :show-overflow-tooltip="true" width="200"></el-table-column>
      <el-table-column prop="datasourceGroup" label="数据源分组" :show-overflow-tooltip="true" width="100"></el-table-column>
      <el-table-column prop="jdbcUrl" label="jdbc_url" :show-overflow-tooltip="true" width="400"></el-table-column>
      <el-table-column prop="zkAddress" label="ZK地址" :show-overflow-tooltip="true" width="200"></el-table-column>
      <el-table-column prop="databaseName" label="数据库名称" :show-overflow-tooltip="true" width="200"></el-table-column>
      <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini"
                     type="text"
                     icon="el-icon-edit"
                     @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />
    <!-- 添加或修改菜单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-form-item label="数据源" prop="datasource">
            <el-select v-model="value" value-key="type" placeholder="请选择" @change="change" style="width: 100%">
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.id"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="数据源名称" prop="datasourceName">
            <el-input v-model="form.datasourceName" placeholder="请输入数据源名称"></el-input>
          </el-form-item>
          <el-form-item label="数据源分组" prop="datasourceGroup">
            <el-input v-model="form.datasourceGroup" placeholder="Default"></el-input>
          </el-form-item>
        </el-row>
        <el-row v-if="form.datasource != 'hbase'">
          <el-col :span="12">
            <el-form-item label="用户名" prop="jdbcUsername">
              <el-input v-model="form.jdbcUsername" placeholder="请输入用户名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="jdbcPassword">
              <el-input v-model="form.jdbcPassword" show-password ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="jdbc url" prop="jdbcUrl">
            <el-input
              type="textarea"
              placeholder="请输入内容"
              v-model="form.jdbcUrl">
            </el-input>
          </el-form-item>
          <el-form-item label="zk地址" v-if="form.datasource === 'hbase'" prop="zdAddress">
            <el-input v-model="form.zdAddress"></el-input>
          </el-form-item>
          <el-form-item label="jdbc驱动类" v-if="showDrive">
            <el-input v-model="form.jdbcDriverClass" readonly></el-input>
          </el-form-item>
          <el-form-item label="数据库名称" v-if="form.datasource === 'mongodb'" prop="databaseName">
            <el-input v-model="form.databaseName"></el-input>
          </el-form-item>
          <el-form-item label="注释" prop="comments">
            <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
              v-model="form.comments">
            </el-input>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button type="primary" @click="test">测试连接</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
  import { listDatasource, testConnect, updateDatasource, addDataSource, delDataSource } from '@/api/metadata/datasource'
  // import { updateDataSource } from '../../../api/metadata/datasource'
  import Cookies from 'js-cookie'

  export default {
    name: 'Datasource',
    data() {
      return {
        loading: true,
        total: 0,
        title: '',
        open: false,
        value: '',
        showDrive: true,
        name: undefined,
        options: [
          {
            'id': 'mysql',
            'value': {
              'type': 'mysql',
              'jdbcUrl': 'jdbc:mysql://{host}:{port}/{database}',
              'jdbcDriverClass': 'com.mysql.jdbc.Driver'
            }
          }, {
            'id': 'oracle',
            'value': {
              'type': 'oracle',
              'jdbcUrl': 'jdbc:oracle:thin:@//{host}:{port}/{database}',
              'jdbcDriverClass': 'oracle.jdbc.OracleDriver'
            }
          }, {
            'id': 'postgresql',
            'value': {
              'type': 'postgresql',
              'jdbcUrl': 'jdbc:postgresql://{host}:{port}/{database}',
              'jdbcDriverClass': 'org.postgresql.Driver'
            }
          }, {
            'id': 'sqlserver',
            'value': {
              'type': 'sqlserver',
              'jdbcUrl': 'jdbc:sqlserver://{host}:{port};DatabaseName={database}',
              'jdbcDriverClass': 'com.microsoft.sqlserver.jdbc.SQLServerDriver'
            }
          }, {
            'id': 'hive',
            'value': {
              'type': 'hive',
              'jdbcUrl': 'jdbc:hive2://{host}:{port}/{database}',
              'jdbcDriverClass': 'org.apache.hive.jdbc.HiveDriver'
            }
          }, {
            'id': 'hbase',
            'value': {
              'type': 'hbase',
              'jdbcUrl': '',
              'jdbcDriverClass': ''
            }
          }, {
            'id': 'mongodb',
            'value': {
              'type': 'mongodb',
              'jdbcUrl': '{host}:{host}',
              'jdbcDriverClass': ''
            }
          }],
        datasourceList: [],
        queryParams: {
          current: 1,
          size: 10
        },
        form: {},
        rules: {
          datasource: [
            { required: true, message: '源数据不能为空', trigger: 'blur' }
          ],
          datasourceName: [
            { required: true, message: '数据源名称不能为空', trigger: 'blur' },
            { max: 100, message: '最大长度为100个字符', trigger: 'blur' }
          ],
          jdbcUrl: [
            { required: true, message: 'jdbc url不能为空', trigger: 'blur' },
            { max: 250, message: '最大长度为250个字符', trigger: 'blur' }
          ],
          jdbcUsername: [
            { max: 50, message: '最大长度为50个字符', trigger: 'blur' }
          ],
          jdbcPassword: [
            { max: 50, message: '最大长度为50个字符', trigger: 'blur' }
          ],
          zdAddress: [
            { max: 50, message: '最大长度为50个字符', trigger: 'blur' }
          ],
          databaseName: [
            { max: 25, message: '最大长度为25个字符', trigger: 'blur' }
          ],
          comments: [
            { max: 500, message: '最大长度为500个字符', trigger: 'blur' }
          ]
        }

      }
    },
    methods: {
      getList() {
        this.loading = true;
        listDatasource(this.queryParams).then(response => {
          this.datasourceList = response.data.records;
          this.total = response.data.total;
          this.loading = false;

        })
      },
      handleQuery() {
        this.getList();
      },
      handleAdd(row) {
        this.reset();
        this.open = true;
        this.title = '添加数据源'

      },
      handleUpdate(row) {
        this.reset()
        this.form = row;
        this.value = row.datasource;
        this.open = true;
        this.title = '修改数据源';

      },
      handleDelete(row) {
        const id = row.id;
        this.$confirm('是否确认删除此数据源?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delDataSource(id);
        }).then(()=>{
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function (){});

      },
      submitForm() {
        this.$refs['form'].validate(valid => {
          if (valid) {
            if (this.form.id != undefined) {
              updateDataSource(this.form).then(response => {
                if (response.code === 0) {
                  this.msgSuccess('修改成功')
                  this.open = false;
                  this.getList();
                }
              })
            } else {
              addDataSource(this.form).then(response => {
                if (response.code === 0) {
                  this.msgSuccess('新增成功');
                  this.open = false;
                  this.getList();
                }
              });
            }
          }
        })
      },
      cancel() {
        this.open = false;
        this.reset();
      },
      reset() {
        this.form = {
          datasource: undefined,
          datasourceName: undefined,
          datasourceGroup: undefined,
          jdbcUsername: undefined,
          jdbcPassword: undefined,
          jdbcUrl: undefined,
          zdAddress: undefined,
          jdbcDriverClass: undefined,
          databaseName: undefined,
          comments: undefined,
          updateBy: Cookies.get("username")
        };
        this.value = '';
        this.resetForm('form');

      },
      change(val) {
        this.form.jdbcUrl = val.jdbcUrl
        this.form.jdbcDriverClass = val.jdbcDriverClass
        this.form.datasource = val.type
        this.showDrive = val.type !== 'hbase' && val.type !== 'mongodb'
      },
      test() {
        this.$refs['form'].validate(valid => {
          if (valid) {
            testConnect(this.form).then(response => {
              if (response.code === 0) {
                this.msgSuccess('测试成功');
              }
            })
          }
        })

      }
    },
    created() {
      this.getList();
      this.reset();
    },
    computed: {}
  }
</script>
